package com.chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * 接收消息
 */
public class TalkReceive implements Runnable{

    DatagramSocket socket = null;
    private int fromIP;
    private String formMsg;

    public TalkReceive(int fromIP, String formMsg) {
        this.fromIP = fromIP;
        this.formMsg = formMsg;
        try{
            socket = new DatagramSocket(this.fromIP);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try{
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);// 阻塞式接收包裹
                byte[] data = packet.getData();
                String s = new String(data, 0, data.length);
                System.out.println(this.formMsg+"："+s);
                if (s.equals("bye")) {
                    break;
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 关闭资源
        socket.close();
    }
}
